from fastapi import APIRouter, Request
from utils import create_json_response
import os
from datetime import datetime

router = APIRouter()

@router.post("/profile/logout")
@router.get("/profile/logout")
async def profile_logout(request: Request):
    """退出登录接口 - 处理退出并记录日志"""
    
    # 创建日志目录
    log_dir = "logs"
    if not os.path.exists(log_dir):
        os.makedirs(log_dir, exist_ok=True)
    
    # 生成日志文件名
    log_file = os.path.join(log_dir, "logout.log")
    
    # 获取客户端信息
    client_ip = request.client.host if request.client else "unknown"
    user_agent = request.headers.get("user-agent", "unknown")
    
    # 记录退出信息
    logout_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    log_entry = f"[{logout_time}] 用户退出登录 - IP: {client_ip} - User-Agent: {user_agent}\n"
    
    try:
        # 写入退出日志
        with open(log_file, "a", encoding="utf-8") as f:
            f.write(log_entry)
        
        # 同时创建一个单独的退出成功标记文件
        success_file = os.path.join(log_dir, "logout_success.txt")
        with open(success_file, "w", encoding="utf-8") as f:
            f.write(f"logout_success_{logout_time}")
            
    except Exception as e:
        # 如果写入失败，仍然返回成功，但不记录日志
        pass
    
    # 返回退出成功响应
    return create_json_response({
        "logout": "success"
    })